from flask_restplus import Namespace, Resource, fields
from app.extensions import db
from app.models import Blog, User
from datetime import datetime
from flask import request
from .auth import auth, g


api = Namespace('blogs', description='博客资源')

doc = {
    'params': {'page': '页码'},   # GET参数
    'description': '描述',        # 描述
    'responses': {403: 'forbidden', 404: 'page not found'},     # 响应
}
parent = api.model('Parent', {
    'title': fields.String,
    'content': fields.String(discriminator=True),
    'praise_num': fields.Integer(discriminator=True)
})


@api.route('/<int:bid>/', '/')
class BlogResource(Resource):
    def get(self, bid):
        blog = Blog.query.get(bid)
        if blog:
            blog_list = []
            blog_list.append({'title': blog.title,
                              'content': blog.content,
                              'datetime': blog.datetime,
                              'praise_num': blog.praise_num})
            return blog_list[0]
        return '没有这个博客'

    @auth.login_required
    def put(self, bid):
        blog = Blog.query.get(bid)
        if blog:
            if g.data['username'] == User.query.get(blog.uid).username:
                blog.title = request.form.get('title')
                blog.content = request.form.get('content')
                blog.datetime = datetime.now()
                return '更新完成'
            return '没有权限更改'
        return '没有这个博客'

    @auth.login_required
    def delete(self, bid):
        blog = Blog.query.get(bid)
        if blog:
            if g.data['username'] == User.query.get(blog.uid).username:
                db.session.delete(blog)
                return '数据已删除'
            return '没有权限删除'
        return '没有这个博客'


@api.route('/push/')
class BlogsListResource(Resource):
    @auth.login_required
    def post(self):
        user = User.query.filter_by(username=g.data['username']).first()
        praise_num = 0
        if request.form.get('title'):
            title = request.form.get('title')
        else:
            return '标题不能为空'
        content = request.form.get('content')
        if request.form.get('parise_num'):
            praise_num = request.form.get('parise_num')
        blog = Blog(title=title, content=content, datetime=datetime.now(), praise_num=praise_num, uid=user.id)
        db.session.add(blog)
        return user.name + '发表了一篇博客，标题是：' + title, str(blog.id)

    @auth.login_required
    def get(self):
        user = User.query.filter_by(username=g.data['username']).first()
        blogs = user.blogs.all()
        return ', '.join(b.title for b in blogs)


